from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_login import UserMixin

from config import Config

db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'  # 设置登录视图

def create_app():
    # 创建 Flask 应用
    app = Flask(__name__)
    app.config.from_object('config.Config')  # 从配置对象加载配置

    # 从config文件导入路径配置
    app.config.from_object(Config)

    # 初始化数据库和登录管理器
    db.init_app(app)
    login_manager.init_app(app)

    # 导入模型以确保它们在数据库初始时被识别
    with app.app_context():
        from .models.models import Users, Courses, Classes, Assignments, Submissions
        db.create_all()  # 创建数据库表

    # 用户加载函数，用于从数据库加载用户
    @login_manager.user_loader
    def load_user(user_id):
        return Users.query.get(int(user_id))

    # 注册蓝图
    from .routes.auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .routes.main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .routes.courses import courses
    from .routes.classes import classes
    from .routes.assignments import assignments
    from .routes.grades import grades
    from .routes.users import users
    app.register_blueprint(courses, url_prefix='/courses')
    app.register_blueprint(classes, url_prefix='/classes')
    app.register_blueprint(assignments, url_prefix='/assignments')
    app.register_blueprint(grades, url_prefix='/grades')
    app.register_blueprint(users, url_prefix='/users')
    return app

